package com.navinfo.platform.fault.utils;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 沈东生
 */
public class CommonUtils {

    /**
     * 获取当前日期对应的周一日期
     *
     * @param date
     * @return
     */
    public static String getMondyStr(Date date) {
        String monday = new SimpleDateFormat("yyyyMMdd").format(getWeekFirstDay(date));
        return monday;
    }

    /**
     * 获取当前日期对应的周一日期
     *
     * @param date
     * @return
     */
    public static String getMonthStr(Date date) {
        String monday = new SimpleDateFormat("yyyyMM").format(getMonthFirstDay(date));
        return monday;
    }

    public static Date getMonthFirstDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    public static Date getWeekFirstDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    public static final String DATETYPE_MONTH = "month";
    public static final String DATETYPE_WEEK = "week";


    public static String getDurationStr(long timeS) {
        String str = "";
        if (timeS < 0) {
            str += "负";
            timeS = -timeS;
        }
        long d = timeS / 86400;
        long h = timeS % 86400 / 3600;
        long m = (timeS % 3600) / 60;
        long s = (timeS) % 60;

        if (d > 0) {
            str += d + "日";
        }
        if (h > 0) {
            str += h + "时";
        }
        if (m > 0) {
            str += m + "分";
        }
        if (s > 0) {
            str += s + "秒";
        }
        return str;
    }

    /**
     * 保留n位小数
     *
     * @param f        小数
     * @param newScale 保留几位
     * @return
     */
    public static double persist(double f, int newScale) {
        BigDecimal bg = new BigDecimal(f);
        double f1 = bg.setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    public static long getToBinary(long num, int index) {
        return (num & (0x1 << index)) >> index;
    }

    public static List<String> getRealCollectionNames(String collectionName, Date startDate, Date endDate, String collectionSplitInterval, String dateFormat) {
        List<String> list = new ArrayList<>();
        if (startDate == null) {
            startDate = new Date();
        }
        if (endDate == null) {
            endDate = new Date();
        }
        if (StringUtils.equalsIgnoreCase(collectionSplitInterval, DATETYPE_WEEK)) {
            Date date = getWeekFirstDay(startDate);
            Date date2 = getWeekFirstDay(endDate);
            while (date.getTime() <= date2.getTime()) {
                list.add(collectionName + "_" + formatDate(date, dateFormat));
                date = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000L);
            }
        } else {
            Date date = getMonthFirstDay(startDate);
            Date date2 = getMonthFirstDay(endDate);
            while (date.getTime() <= date2.getTime()) {
                list.add(collectionName + "_" + formatDate(date, dateFormat));
                date = getMonthFirstDay(getNextMonth(date));
            }
        }

        return list;
    }

    public static String formatDate(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(
                dateFormat);
        return sdf.format(date);
    }

    private static Date getNextMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setTime(date);
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
        return cal.getTime();
    }

    public static String getRealPath(String path, Date date) {
        String toPath = path;
        toPath = replaceOneDate(toPath, date, "date");

        return toPath;
    }

    private static String replaceOneDate(String path, Date d, String prefix) {
        String pattern = "(\\{" + prefix + ":[^\\}]+\\})";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(path);
        if (m.find()) {
            String findStr = m.group(1);
            String formatStr = findStr.replace("{"+prefix+":", "").replace("}", "");
            String dateStr = formatDate(d, formatStr);
            return path.replace(findStr, dateStr);
        }
        return path;
    }



    public static Date addDays(Date date, int i) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
        return cal.getTime();
    }




    /**
     * 将驼峰字符串转为下划线分隔的形式，如terminalId => terminal_id
     * @param name
     * @return
     */
    public static String strCamelToSnakeCase(String name) {
        if(name==null||"".equalsIgnoreCase(name)){
            return "";
        }
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<name.length();i++){
            char ch=name.charAt(i);
            if(Character.isUpperCase(ch)){
                sb.append("_").append(Character.toLowerCase(ch));
            }else{
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    /**
     * 将list中的数据toString后用spliter作为分隔符，返回一个大的字符串
     *
     * @param list
     * @param spliter
     * @return
     */
    public static String mkString(Collection<?> list, String spliter) {
        StringBuilder sb1 = new StringBuilder();
        int i = 0;
        for (Object s : list) {
            if (s == null) {
                continue;
            }
            if (i != 0) {
                sb1.append(spliter);
            }
            sb1.append(s);
            i++;
        }
        return sb1.toString();
    }

    /**
     * 判断集合是否为空
     * @param collection
     * @return
     */
    public static boolean isCollectionEmpty(Collection<?> collection) {
        return collection == null || collection.size() == 0;
    }

    /**
     * 判断集合不为空
     * @param collection
     * @return
     */
    public static boolean isCollectionNotEmpty(Collection<?> collection) {
        return !isCollectionEmpty(collection);
    }


    public static List<String> splitStr(String str, String spliter) {
        List<String> list = new ArrayList<>();
        if (str != null) {
            String[] ss = str.split(spliter);
            for (String f : ss) {
                list.add(f.trim());
            }
        }
        return list;
    }

}
